package com.fallsvc.re.networkprogramming.timer;

import java.util.PriorityQueue;

public class MyTimer {
    // 核⼼结构
    private PriorityQueue<MyTask> queue = new PriorityQueue<>();
    // 创建⼀个锁对象
    private Object locker = new Object();

    public void schedule(Runnable runnable, long delay) {
// 根据参数, 构造 MyTask, 插⼊队列即可.
        synchronized (locker) {
            MyTask myTask = new MyTask(runnable, delay);
            queue.offer(myTask);
            locker.notify();
        }
    }

    // 在这⾥构造线程, 负责执⾏具体任务了.
    public MyTimer() {
        Thread t = new Thread(() -> {
            while (true) {
                try {
                    synchronized (locker) {
// 阻塞队列, 只有阻塞的⼊队列和阻塞的出队列, 没有阻塞的查看队⾸元素.
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        MyTask myTask = queue.peek();
                        long curTime = System.currentTimeMillis();
                        if (curTime >= myTask.time) {
// 时间到了, 可以执⾏任务了
                            queue.poll();
                            myTask.runnable.run();
                        } else {
// 时间还没到
                            locker.wait(myTask.time - curTime);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }

}